
package backupUtility;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
/**
 * @author Changcoco Kevin Paolo
 * @author Mamis Dominique Bernard
 * @author Palasi Jandy
 * @author Rafael Ian Paolo 
 */
public class AddToBackupUI  extends JFrame implements ActionListener{
    private JPanel scrollPanel;
    private JPanel buttonPanel;
    private JScrollPane scrollPane;
    private JTable choicesTable;
    private JButton saveButton;
    private JButton cancelButton;
    private JButton finalize;
    private JLabel chooseLabel;
    private ArrayList<File> arrayListofFiles;
    private File chosen;
    private String pass;
    private DefaultTableModel model;
    private File thisOne;
    private String password;
    public AddToBackupUI(File chosen, String pass){
       thisOne = chosen;
       password = pass;
        arrayListofFiles = new ArrayList<File>();
        try{
             ZipFile zip = new ZipFile(chosen);
              if(zip.isEncrypted()){
                zip.setPassword(pass);
                String path = chosen.getParentFile().getPath();
                zip.extractAll(path);
                 File[] listOfFiles = chosen.getParentFile().listFiles();
                  for(File f : listOfFiles){
                   arrayListofFiles.add(f);
              }
                  arrayListofFiles.remove(chosen);
              }
         }catch(ZipException ex) {
			JOptionPane.showMessageDialog(null, "Wrong password!!!");
          }catch(Exception e){}
        Object [] columnNames = {"File Name", "Save"};
        Object [][] fileNames = new Object[arrayListofFiles.size()][2];
        for(int i = 0; i < fileNames.length; i++){
            fileNames[i][0] = arrayListofFiles.get(i).getName();
            fileNames[i][1] = true;
        }
        
        model= new DefaultTableModel(fileNames, columnNames);
        choicesTable = new JTable(model) {
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    default:
                        return Boolean.class;
                }
            }
        
           public boolean isCellEditable(int row, int column) {
            return column == 1;
            }
        };
        
        setLayout(new BorderLayout());
	JLabel background=new JLabel(new ImageIcon("/backupUtility/back.jpg"));
	add(background);
	background.setLayout(new FlowLayout());
        
        choicesTable.setPreferredScrollableViewportSize(choicesTable.getPreferredSize());
        choicesTable.getColumnModel().getColumn(0).setPreferredWidth(660);
        choicesTable.getColumnModel().getColumn(1).setPreferredWidth(40);
        
        scrollPane = new JScrollPane(choicesTable);
        scrollPane.setPreferredSize(new Dimension(700,400));
        
        saveButton = new JButton("Move files into Backup");
        saveButton.addActionListener(this);
        
        cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(this);
        
        finalize = new JButton("Save");
        finalize.addActionListener(this);
         
        chooseLabel = new JLabel("Select Files to add to backup: ");
      
        scrollPanel = new JPanel();
        scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.PAGE_AXIS));
        scrollPanel.add(chooseLabel);
        scrollPanel.add(Box.createRigidArea(new Dimension(0,5)));
        scrollPanel.add(scrollPane);
        scrollPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
        scrollPanel.setBackground(new Color(0,0,0,64));

        buttonPanel = new JPanel();
        buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        buttonPanel.add(Box.createHorizontalGlue());
        buttonPanel.add(saveButton);
        buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonPanel.add(finalize);
        buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
        buttonPanel.add(saveButton);
        buttonPanel.setBackground(new Color(0,0,0,64));
        
        Container contentPane = getContentPane();
        contentPane.add(scrollPanel, BorderLayout.CENTER);
        contentPane.add(buttonPanel, BorderLayout.PAGE_END);

        pack();
        setVisible(true);
        setSize(800,500);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
      
    }
    
    @SuppressWarnings("empty-statement")
    public void actionPerformed(ActionEvent ae){
        if(ae.getSource()==saveButton){
             final JFileChooser fileChooser = new JFileChooser(new File("C:/User/Nikzter/Desktop/"));
      fileChooser.setFileFilter(new FileFilter(){      
       public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
           return false;
        }

        public String getDescription() {
            return "Directories";
        }
    });
    fileChooser.showOpenDialog(this);
    File chosen = fileChooser.getSelectedFile();
     arrayListofFiles.add(chosen);
    try{
       Object [][] addFile = {{chosen.getName(), true}};
        model.addRow(addFile);
    }catch(Exception e){}
    
        }else if(ae.getSource()==cancelButton){
            new BackupUtilityUI().setVisible(true);
            dispose();
            
        }else if(ae.getSource()==finalize){
             ArrayList<File> selectedFiles;
            selectedFiles = new ArrayList<File>();
        for(int i = 0; i < choicesTable.getRowCount(); i++){
            if(choicesTable.getModel().getValueAt(i,1) == true){
                selectedFiles.add(arrayListofFiles.get(i));
                System.out.println(selectedFiles.get(i).getName());
            }
        }
           String path = thisOne.getPath();
           ZipBackup zipper = new ZipBackup(selectedFiles, path, thisOne.getAbsolutePath(), password);
               for(File f : arrayListofFiles){
                   f.delete();
              }
               JOptionPane.showMessageDialog(null, "Successfully edited backup.");
               new BackupUtilityUI().setVisible(true);
               dispose();
        }
    }
}
